package cn.yto.print.utils;

import cn.hutool.json.JSONUtil;
import cn.yto.print.config.PrintLinkedContext;
import cn.yto.print.model.response.PrintTaskResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.Session;
import java.io.IOException;

public class WebSocketUtil {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketUtil.class);

    /**
     * 发送响应消息
     */
    public static void sendSocketMessage(Session session, PrintTaskResponse printTaskResponse) {
        if (session == null || !session.isOpen()) {
            return;
        }
        try {
            String responseStr = JSONUtil.toJsonStr(printTaskResponse);
            logger.info("发送给前端响应报文：{}", responseStr);
            session.getBasicRemote().sendText(responseStr);
        } catch (IOException e) {
            logger.error("发送给前端响应报文异常: ", e);
        }
    }

    /**
     * 发送缓存消息
     */
    public static void sendCacheMessage(PrintTaskResponse printTaskResponse) {
        Session session = PrintLinkedContext.getSession(printTaskResponse.getSessionId());
        if (null == session) {
            ExpiredMsgUtil.addExpiredMessage(printTaskResponse);
        } else {
            sendSocketMessage(session, printTaskResponse);
        }
    }

}
